<template>
  <div class="crud-container">
    <!-- Header / Actions -->
    <div class="crud-header">
      <el-input
        v-model="query.keyword"
        placeholder="搜索名称或邮箱…"
        clearable
        class="search-input"
        @clear="handleSearch"
        @keyup.enter="handleSearch"
      />
      <el-select v-model="query.role" placeholder="角色" clearable class="role-select">
        <el-option label="全部" :value="''" />
        <el-option label="Admin" value="admin" />
        <el-option label="Editor" value="editor" />
        <el-option label="Viewer" value="viewer" />
      </el-select>
      <el-button type="primary" @click="handleSearch" icon="Search">
        搜索
      </el-button>
      <el-button @click="resetFilters" icon="Refresh">
        重置
      </el-button>
      <div class="flex-spacer"></div>
      <el-button type="success" @click="openCreate" icon="Plus">新建</el-button>
      <el-button type="danger" :disabled="!multipleSelection.length" @click="batchDelete" icon="Delete">批量删除</el-button>
    </div>

    <!-- Table -->
    <el-card shadow="hover" class="crud-card">
      <el-table
        :data="rows"
        border
        stripe
        size="small"
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
      >
      <el-table-column
      v-for="col in columns"
      :key="col.prop"
      v-bind="col"
      >
      <template #default="scope">
        <span>
          {{ col.formatter ? col.formatter(scope.row[col.prop]) : scope.row[col.prop] }}
        </span>
      </template>
      </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button size="small" type="primary" link @click="openEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" link @click="remove(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- Pagination -->
      <div class="pagination-wrapper">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[5,10,20,50]"
          :page-size="pagination.pageSize"
          :current-page="pagination.current"
          :total="filteredData.length"
          @size-change="(s)=> (pagination.pageSize=s)"
          @current-change="(p)=> (pagination.current=p)"
        />
      </div>
    </el-card>

    <!-- Create/Edit Dialog -->
    <el-dialog v-model="dialog.visible" :title="dialog.mode==='create' ? '新建用户' : '编辑用户'" width="520px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="88px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="张三" clearable />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="user@example.com" clearable />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="form.role" placeholder="请选择">
            <el-option label="Admin" value="admin" />
            <el-option label="Editor" value="editor" />
            <el-option label="Viewer" value="viewer" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialog.visible=false">取消</el-button>
          <el-button type="primary" @click="submit">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, computed, watch } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { onMounted } from 'vue'
import { getRowsApi } from '@/api/test_api/getRowsApi'
import { h } from 'vue'
import { ElTag } from 'element-plus'
const getRows = async (pagination) => {
  const result = await getRowsApi(pagination)
  console.log(result);
  // rows.value = result.records
}
onMounted(()=>{
  // 获取rows数据
  getRows(pagination)
})

// Mock 数据
const rows = ref([
  { id: 1, name: 'Alice', email: 'alice@example.com', role: 'admin', createdAt: Date.now()-86400000*3 },
  { id: 2, name: 'Bob', email: 'bob@example.com', role: 'editor', createdAt: Date.now()-86400000*2 },
  { id: 3, name: 'Carol', email: 'carol@example.com', role: 'viewer', createdAt: Date.now()-86400000*7 },
])

const columns = [
  { prop: 'id', label: 'ID', width: 80, sortable: 'custom' },
  { prop: 'name', label: '姓名' },
  { prop: 'email', label: '邮箱' },
  {
    prop: 'role',
    label: '角色',
  },
  {
    prop: 'createdAt',
    label: '创建时间',
    sortable: 'custom',
    formatter: (val) => new Date(val).toLocaleString(),
  },
]


// 查询（关键词，角色）
const query = reactive({ keyword: '', role: '' })
//根据某个字段排序
const sortState = reactive({ prop: '', order: '' })
// 分页参数
const pagination = reactive({ pageNo: 1, pageSize: 10 })
// 查询关键词或角色变化时，过滤数据
const filteredData = computed(() => {
  const kw = query.keyword.trim().toLowerCase()
  return rows.value.filter(r => {
    const hitKW = !kw || r.name.toLowerCase().includes(kw) || r.email.toLowerCase().includes(kw)
    const hitRole = !query.role || r.role === query.role
    return hitKW && hitRole
  })
})

const sortedData = computed(() => {
  const data = [...filteredData.value]
  if (!sortState.prop || !sortState.order) return data
  data.sort((a,b)=>{
    const av = a[sortState.prop]
    const bv = b[sortState.prop]
    if (av === bv) return 0
    const res = av > bv ? 1 : -1
    return sortState.order === 'asc' ? res : -res
  })
  return data
})

const pagedData = computed(() => {
  const start = (pagination.pageNo - 1) * pagination.pageSize
  return sortedData.value.slice(start, start + pagination.pageSize)
})

watch([() => query.keyword, () => query.role], () => { pagination.pageNo = 1 })

function handleSearch() {}

function resetFilters(){ query.keyword=''; query.role=''; pagination.pageNo=1 }

function handleSortChange({ prop, order }){
  sortState.prop = prop || ''
  sortState.order = order === 'ascending' ? 'asc' : order === 'descending' ? 'desc' : ''
}

// 选择 / 批量操作
const multipleSelection = ref([])
function handleSelectionChange(val){ multipleSelection.value = val }

// 新建 / 编辑
const dialog = reactive({ visible:false, mode: 'create', editId: 0 })
const formRef = ref()
const form = reactive({ name:'', email:'', role:'' })
const rules = {
  name: [ { required: true, message: '请输入姓名', trigger: 'blur' } ],
  email:[ { required: true, message: '请输入邮箱', trigger: 'blur' }, { type:'email', message:'邮箱格式不正确', trigger:'blur' }],
  role: [ { required: true, message: '请选择角色', trigger: 'change' } ],
}

// 点击新建按钮后将dialog的模式设置为'create'，清空表单数据并显示对话框，将editIds设置为0
function openCreate(){
  dialog.mode = 'create'
  dialog.editId = 0
  Object.assign(form, { name:'', email:'', role:'' })
  dialog.visible = true
}

// 点击新建按钮后将dialog的模式设置为'edit'，填充表单数据并显示对话框，将editIds设置为当前行的id
function openEdit(row){
  dialog.mode = 'edit'
  dialog.editId = row.id
  Object.assign(form, { name: row.name, email: row.email, role: row.role })
  dialog.visible = true
}
// 提交表单
function submit(){
  formRef.value.validate((valid)=>{
    if(!valid) return
    if(dialog.mode==='create'){
      const maxId = rows.value.reduce((m,r)=>Math.max(m,r.id), 0)
      rows.value.unshift({ id: maxId+1, name: form.name, email: form.email, role: form.role, createdAt: Date.now() })
    }else{
      const idx = rows.value.findIndex(r=>r.id===dialog.editId)
      if(idx>-1){
        rows.value[idx] = { ...rows.value[idx], name: form.name, email: form.email, role: form.role }
      }
    }
    dialog.visible=false
  })
}

// 单个删除
function remove(id) {
  ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    console.log(rows.value);
    rows.value = rows.value.filter(r => r.id !== id)
    
    
    ElMessage.success('删除成功')
  }).catch(() => {
    // 取消删除
  })
}

// 批量删除
function batchDelete() {
  if (!multipleSelection.value.length) return
  ElMessageBox.confirm(`确定要删除选中的 ${multipleSelection.value.length} 条记录吗？`, '批量删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    const ids = new Set(multipleSelection.value.map(i => i.id))
    rows.value = rows.value.filter(r => !ids.has(r.id))
    multipleSelection.value = []
    ElMessage.success('批量删除成功')
  }).catch(() => {
    // 取消操作
  })
}

// 工具方法
function roleTagType(role){ return role==='admin' ? 'danger' : role==='editor' ? 'warning' : 'success' }
function formatDate(ts){
  const d = new Date(ts)
  const pad = (n)=> n.toString().padStart(2,'0')
  return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
}
</script>

<style scoped>
.crud-container { 
    padding: 24px; background: #f8fafc;
 }
.crud-header {
  display: flex; align-items: center; gap: 12px; margin-bottom: 16px;
  padding: 12px; background: #fff; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}
.search-input { width: 240px; }
.role-select { width: 140px; }
.flex-spacer { flex: 1; }

.crud-card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.06);
  overflow: hidden;
}

.pagination-wrapper {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

.el-dialog {
  border-radius: 12px;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
